package com.cloudptt.wp.lock;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.telephony.TelephonyManager;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.cloudptt.api.product.Product;
import com.cloudptt.api.product.adapter.GCallEventAdapter;
import com.cloudptt.api.product.adapter.ICallInfoDesc;
import com.cloudptt.api.product.log.Log;
import com.cloudptt.wp.R;
import com.cloudptt.wp.SysApplication;

import java.text.SimpleDateFormat;

public class LockScreenActivity extends AppCompatActivity implements View.OnTouchListener,ICallInfoDesc {
    public final static String TAG = "LockScreenActivity";
    private KeyGuardReceiver mKeyGuardReceiver;
    private Handler handler = new Handler();
    private TextView mDateView;
    private TextView mGroupNameView;
    private TextView mFloorNameView;
    private TextView secTv;
    private String lastFloorStr = "";
    private String lastSosStr = "";
    private Product product = null;
    private ImageView figerBtn = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Parser.KEY_GUARD_INSTANCES.add(this);

        Window window = getWindow();
        window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        window.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
//                | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
//                | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON |
//                WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
        );

        registerKeyGuardReceiver();//屏蔽Home

        setContentView(R.layout.activity_lock_screen);

        initViews();

        Parser.killBackgroundProcess(this);
        wakeUpAndUnlock();
    }

    private void initViews() {
        mDateView = (TextView) findViewById(R.id.dateTv);
        String dateString = Parser.getDataStr();
        mDateView.setText(dateString);
        mGroupNameView = (TextView) findViewById(R.id.groupName);
        mFloorNameView = (TextView) findViewById(R.id.floorName);
        secTv = (TextView) findViewById(R.id.secTv);

        figerBtn = (ImageView) findViewById(R.id.fingerBtn);
        figerBtn.setOnTouchListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        SysApplication.IsLockScreen = true;
        SysApplication app = ((SysApplication) getApplicationContext());
        Product product = app.getProduct();
//        product.setSysListener(this);

        if( product != null)
        {
            GCallEventAdapter callEventAdapter = product.getGCallEventAdapter();
            callEventAdapter.setCallInfoDesc(this);
//            lastFloorStr = callEventAdapter.getLastFloorStr();
//            mFloorNameView.setText(lastFloorStr);
//            callEventAdapter.setUpdateUiListener(this);
        }
        updateGroupName();
//        resetSvrStatueDscp();
    }
    public void updateGroupName() {
        Log.i(TAG, " updateGroupName" );
        if(product == null)
        {
            SysApplication app = ((SysApplication) getApplicationContext());
            product = app.getProduct();
        }

        if (product != null && product.getCurGroupInfo() != null) {
            String groupName = product.getCurGroupInfo().getName();
            Log.i(TAG, " updateGroupName groupName = " + groupName);
            mGroupNameView.setText(groupName);
        } else {
            mGroupNameView.setText("");
        }
        mFloorNameView.setText(lastFloorStr);
    }


    @Override
    public void onBackPressed() {

    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        int key = event.getKeyCode();
        switch (key) {
            case KeyEvent.KEYCODE_BACK: {
                return true;
            }
            case KeyEvent.KEYCODE_MENU: {
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    private void registerKeyGuardReceiver() {
        if (null == mKeyGuardReceiver) {
            mKeyGuardReceiver = new KeyGuardReceiver();
            registerReceiver(mKeyGuardReceiver, new IntentFilter());
        }
    }

    private void unregisterKeyGuardReceiver() {
        if (mKeyGuardReceiver != null) {
            unregisterReceiver(mKeyGuardReceiver);
        }
    }

    private Runnable r = new Runnable() {
        @Override
        public void run() {
            showToast(R.string.unlock_suc);
            finish();
        }
    };
    private int TOUCH_MAX = 50;
    private int mLastMotionX;
    private int mLastMotionY;
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        int x = (int) event.getX();
        int y = (int) event.getY();
        Log.d(TAG, "onTouch x = " + x + " y" + y);
        Log.d(TAG, "onTouch event.getAction() = " + event.getAction());
        switch (event.getAction()) {
            case MotionEvent.ACTION_UP:
                // 抬起时,移除已有Runnable回调,抬起就算长按了(不需要考虑用户是否长按了超过预设的时间)
                handler.removeCallbacks(r);
                break;
            case MotionEvent.ACTION_MOVE:
                if (Math.abs(mLastMotionX - x) > TOUCH_MAX
                        || Math.abs(mLastMotionY - y) > TOUCH_MAX) {
                    // 移动误差阈值
                    // xy方向判断
                    // 移动超过阈值，则表示移动了,就不是长按(看需求),移除 已有的Runnable回调
                    handler.removeCallbacks(r);
                }
                break;
            case MotionEvent.ACTION_DOWN:
                // 每次按下重新计时
                // 按下前,先移除 已有的Runnable回调,防止用户多次单击导致多次回调长按事件的bug
                handler.removeCallbacks(r);
                mLastMotionX = x;
                mLastMotionY = y;
                figerBtn.setBackgroundResource(R.drawable.finger_pressed);
                // 按下时,开始计时
                handler.postDelayed(r, 1000);
                break;
        }
        return false;//onclick等其他事件不能用请改这里
    }

    @Override
    public void updateCallUser(String callKey, boolean isShow, String userDesc) {
        Log.d(TAG, "updateCallUser callKey = " + callKey + " isShow = " + isShow + " userDesc = " + userDesc);
        wakeUpAndUnlock();
        secTv.setText("MCX");
        mGroupNameView.setText(userDesc);
    }
    public void updateCallInfoDesc(String callKey,int callState,String callInfoDesc)
    {
        mFloorNameView.setText(callInfoDesc);
    }
    @Override
    public void updateFloorInfoDesc(String callKey,int speakState,String floorInfoDesc) {
        Log.d(TAG, "lightControl updateCallInfoDesc callKey = " + callKey + " floorInfoDesc = " + floorInfoDesc);
        wakeUpAndUnlock();
        secTv.setText("MCX");
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                Log.d(TAG, "lightControl lockScreen AFTER");
                lastFloorStr = floorInfoDesc;
                mFloorNameView.setText(lastFloorStr);
//				callRightTextView.setText(callInfoDesc);
                Log.d(TAG, "lightControl lockScreen END");
//					findGroupInfoSetDefault();
            }
        });
    }
    @Override
    public void updateFloorState(String callKey,int speakState,boolean isIdle)
    {}
    @Override
    public void updateSecDesc(String callKey, String secStr) {
        Log.d(TAG, "onSysState secStr = " + secStr);
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                if(!secStr.equals("")) {
                    secTv.setText(secStr);
                    mFloorNameView.setText(lastFloorStr);
                }
            }
        });
    }



    // 4.0以上无法屏蔽Home键，所以没什么作用
    class KeyGuardReceiver extends BroadcastReceiver {

        static final String SYSTEM_REASON = "reason";
        static final String SYSTEM_HOME_KEY = "homekey";// home key
        static final String SYSTEM_RECENT_APPS = "recentapps";// long home key

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
                String reason = intent.getStringExtra(SYSTEM_REASON);
                if (reason != null) {
                    if (reason.equals(SYSTEM_HOME_KEY)) {
                        finish();
                    } else if (reason.equals(SYSTEM_RECENT_APPS)) {
                    }
                }
            } else if (action.equals(TelephonyManager.ACTION_PHONE_STATE_CHANGED) || action.equals(Intent.ACTION_NEW_OUTGOING_CALL)) {
                finish();
            }
        }
    }

    private void showToast(int strId) {
        Toast.makeText(getApplicationContext(), strId, Toast.LENGTH_LONG).show();
    }
    /**
     * 唤醒手机屏幕并解锁
     */
    public void wakeUpAndUnlock() {
        // 获取电源管理器对象
        PowerManager pm = (PowerManager) LockScreenActivity.this.getSystemService(Context.POWER_SERVICE);
        boolean screenOn = pm.isScreenOn();
        if (!screenOn) {
            // 获取PowerManager.WakeLock对象,后面的参数|表示同时传入两个值,最后的是LogCat里用的Tag
            PowerManager.WakeLock wl = pm.newWakeLock(
                    PowerManager.ACQUIRE_CAUSES_WAKEUP |
                            PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "bright");
            wl.acquire(10000); // 点亮屏幕
            wl.release(); // 释放
        }
    }

    @Override
    protected void onDestroy() {
        unregisterKeyGuardReceiver();
        super.onDestroy();
    }

}




